from apps.user.models import UserModel
from apps.user.serializers import TokenModelSerializer
from apps.user.dao import UserDao
from apps.common.utils.fileHeader import *
from apps.common.utils.tools import random_str, random_uuid
from datetime import datetime
from rest_framework.authtoken.models import Token
from apps.system.rank.dao import RankDao

# 新增用户
def createUser(params):
    print('新增用户', params)
    if isEmptyStr(params.get('username')):
        if params.get('phone'):
            params['username'] = random_str(4) + params.get('phone')
        else:
            params['username'] = random_uuid()
    else:
        params['username'] = params.get('username')
    if isEmptyStr(params.get('password')):
        params['password'] = random_uuid()
    else:
        params['password'] = params.get('password')
    if isEmptyStr(params.get('nickname')):
        if len(params.get('phone')) >= 4:
            params['nickname'] = '用户_' + params.get('phone')[len(params.get('phone'))-4: len(params.get('phone'))]
        else:
            params['nickname'] = '用户_' + params.get('phone')
    if isEmptyStr(params.get('role')):
        params['role'] = 'custom'

    # 设置默认rank级别
    _rank = RankDao().findOneByLesseeIdAndGrade(params.get('lessee'), 0)
    if _rank:
        params['rank'] = _rank.id
    else:
        print('员工级别不存在')

    # if isEmptyStr(params.get('checkStatus')):
    #     params['checkStatus'] = 'PASS'
        
    _user = UserDao().create(params)
    _user.code = 100000 + _user.id
    _user.save()
    return _user

def replaceToken(userId):

    old_token = Token.objects.filter(user_id=userId)
    old_token.delete()
    token = Token.objects.create(user_id=userId)

    # 更新最近登录时间
    UserModel.objects.filter(id=userId).update(lastVisitTime=datetime.now())
    return token